﻿using System;
using AccessControl.Contracts.Models;
using AccessControl.Contracts.Settings;
using System.Collections.Generic;
using AccessControl.Data.Models;
using System.Collections.ObjectModel;
using System.Windows.Input;
using AccessControl.Wpf.Commands;

namespace AccessControl.Wpf.Settings.ViewModels
{
	class UsersSettingsViewModel : SettingsBaseViewModel<IUser>
	{
		#region Fields

		ISettingsService _settingsService;
		ObservableCollection<IEntry> _AvailableEntries = new ObservableCollection<IEntry>();

		#endregion

		#region Public Constructor

		public UsersSettingsViewModel(ISettingsService settingsService)
			: base(settingsService.Users)
		{
			Name = "Users";
			_settingsService = settingsService;
			foreach (IEntry entry in settingsService.Entries.Items)
				_AvailableEntries.Add(entry);
		}

		#endregion

		#region Public Properties

		public IList<IEntry> AvailableEntries
		{
			get { return _AvailableEntries; }
		}

		#endregion

		#region Commands

		public ICommand AddAllowedEntryCommand
		{
			get { return new CommandBaseOfT<IEntry>(AddAllowedEntry); }
		}

		public ICommand RemoveAllowedEntryCommand
		{
			get { return new CommandBaseOfT<IEntry>(RemoveAllowedEntry); }
		}

		#endregion

		#region Protected Overrides

		protected override void OnCurrentItemChanged()
		{
			/* Clear */
			_AvailableEntries.Clear();
			/* Fill */
			foreach (IEntry entry in _settingsService.Entries.Items)
				_AvailableEntries.Add(entry);

			/* And remove the allowed ones */
			if (CurrentItem != null)
			{
				foreach (IEntry allowedEntry in CurrentItem.AllowedEntries)
					AvailableEntries.Remove(FindEntryInAvailableEntries(allowedEntry.Id));
			}
		}

		#endregion

		#region SettingsBaseViewModel Overrides

		public override void AddItem(IUser item)
		{
			SettingsService.Add(item);
		}

		public override void EditItem(IUser item)
		{
			SettingsService.Update(item);
		}

		public override void DeleteItem(IUser item)
		{
			SettingsService.Delete(item);
		}

		public override bool IsValidItem(IUser item)
		{
			return true;
		}

		public override IUser CreateNewItem()
		{
			return new User()
			{
				Name = string.Format("New user({0})", SettingsService.Items.Count + 1)
			};
		}

		#endregion

		#region Private Members

		private void AddAllowedEntry(IEntry entry)
		{
			AvailableEntries.Remove(entry);
			CurrentItem.AllowedEntries.Add(entry);
		}

		private void RemoveAllowedEntry(IEntry entry)
		{
			CurrentItem.AllowedEntries.Remove(entry);
			AvailableEntries.Add(entry);
		}

		private IEntry FindEntryInAvailableEntries(int id)
		{
			foreach (IEntry entry in AvailableEntries)
			{
				if (entry.Id == id)
					return entry;
			}

			return null;
		}

		#endregion
	}
}
